package com.whh.util;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class DownFileUtils {
    public static void downloadMyFile(File file, HttpServletResponse response) {
        try {
            //判断要下载文件是否存在
            if (file.exists()) {
                //获取文件名称
                String fileName = file.getName();
                //设置响应头部信息
                response.setHeader("Content-Disposition",
                        "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
                //获取输入流--->读取数据
                InputStream inputStream = new FileInputStream(file);
                //获取输出流--->写入数据
                OutputStream outputStream = response.getOutputStream();
                byte[] buff = new byte[1024];
                int length;
                while ((length = inputStream.read(buff)) != -1) {
                    outputStream.write(buff, 0, length);
                    outputStream.flush();
                }
                outputStream.close();
                inputStream.close();
            } else {
                throw new RuntimeException("文件不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
